import { login, getUserInfo, getUserDetail } from '@/api/user'
import { resetRouter } from '@/router'
import {
  getToken,
  setToken as updateToken,
  removeToken as removeUserToken,
  setTime
} from '@/utils/auth'

const state = {
  // token : localStorage.getItem("token-key")
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    // localStorage.setItem('token-key')
    updateToken(data)
    setTime()
    state.token = data
  },
  removeToken(state) {
    state.token = null
    removeUserToken()
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    try {
      const res = await login(data)
      console.log(res)
      store.commit('setToken', res)
    } catch (err) {
      console.log(err)
    }
  },

  async getUserInfo(store) {
    const userInfo = await getUserInfo()
    const baseInfo = await getUserDetail(userInfo.userId)
    const data = { ...userInfo, ...baseInfo }
    store.commit('setUserInfo', data)
    return data
  },

  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    resetRouter()
    store.commit('permission/setRoutes', [], { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
